package threads.threadlocal;


import java.util.concurrent.atomic.AtomicInteger;


/**
 * ThreadLocalMap 中静态内部类 Entry 是弱引用类型。
 * 弱引用类型的特点是，只要垃圾回收器扫描时发现对象只存在弱引用时，则不管内存是否足够都会回收弱引用对象。
 */
public class Demo02 {
    public static void main(String[] args) {
        for (int i = 0; i < 18848; i++) {
            // 这里的 threadLocal 只存在于 ThreadLocalMap.Entry 的弱引用
            MyThreadLocal threadLocal = new MyThreadLocal();
            UserInfo userInfo = new UserInfo();
            threadLocal.set(userInfo);


            // 不使用如果不执行 remove() 方法则会到导致内存泄露, UserInfo 和 ThreadLocalMap 的实例对象不会被内存回收。
            threadLocal.remove();
        }
        System.out.println("18848 end");


        MyThreadLocal threadLocal = new MyThreadLocal();
        MyThreadLocal threadLocal1 = new MyThreadLocal();
        MyThreadLocal threadLocal2 = new MyThreadLocal();
        threadLocal.set("这是强引用");
        for (int i = 0; i < 666666666; i++) {
            new String("" + i);
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName() + " :" + threadLocal.get());
        System.out.println(Thread.currentThread().getName() + " :" + threadLocal1.get());
        System.out.println(Thread.currentThread().getName() + " :" + threadLocal2.get());

        System.out.println("============== end ===========");
    }

}

class MyThreadLocal extends ThreadLocal {
    private static AtomicInteger count = new AtomicInteger();


    @Override
    protected void finalize() throws Throwable {
        System.out.println("MyThreadLocal finalize() " + count.getAndIncrement());
    }
}

class UserInfo {
    private static AtomicInteger count = new AtomicInteger();

    @Override
    protected void finalize() throws Throwable {
        System.out.println("UserInfo finalize() " + count.getAndIncrement());
    }
}
